package com.walming.generator.support.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.walming.generator.copycat.mybatisplus.service.impl.ServiceImpl;
import com.walming.generator.common.cache.TemplateCacheUtils;
import com.walming.generator.common.constant.Constants;
import com.walming.generator.common.constant.GenConstants;
import com.walming.generator.common.exception.BusinessException;
import com.walming.generator.common.utils.StringUtils;
import com.walming.generator.common.utils.text.Convert;
import com.walming.generator.support.domain.GenTemplate;
import com.walming.generator.support.mapper.GenTemplateMapper;
import com.walming.generator.support.service.IGenTemplateService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 代码生成模版 ServiceImpl
 *
 * @author jianxiao
 * @date 2020/12/18 13:43
 */
@Service
public class GenTemplateServiceImpl extends ServiceImpl<GenTemplateMapper, GenTemplate> implements IGenTemplateService {

    /**
     * 根据模版类型获取模版列表
     *
     * @param templateType 模版类型
     * @param tplCategory  操作模板（crud单表操作 tree树表操作 sub主子表操作）
     * @return List<GenTemplate>
     */
    @Override
    @Cacheable(value = TemplateCacheUtils.GEN_TEMPLATE_CACHE, key = "#templateType + ':' + #tplCategory")
    public List<GenTemplate> selectTemplateByType(String templateType, String tplCategory) {
        LambdaQueryWrapper<GenTemplate> queryWrapper = new LambdaQueryWrapper<GenTemplate>()
                .eq(GenTemplate::getTemplateType, templateType).orderByAsc(GenTemplate::getTemplateSort);
        if (GenConstants.RUO_YI.equals(templateType)) {
            if (GenConstants.TPL_CRUD.equals(tplCategory)) {
                queryWrapper.notIn(GenTemplate::getTemplateName, "tree.html", "list-tree.html", "sub-domain.java");
            } else if (GenConstants.TPL_TREE.equals(tplCategory)) {
                queryWrapper.notIn(GenTemplate::getTemplateName, "list.html", "sub-domain.java");
            } else if (GenConstants.TPL_SUB.equals(tplCategory)) {
                queryWrapper.notIn(GenTemplate::getTemplateName, "tree.html", "list-tree.html");
            }
        }
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 新增保存代码模版信息
     *
     * @param template 模版信息
     * @return 结果
     */
    @Override
    public int saveTemplate(GenTemplate template) {
        template.setByteNum((long) template.getTemplateContent().getBytes().length).setLineNum(1L);
        return baseMapper.insert(template);
    }

    /**
     * 修改保存代码模版信息
     *
     * @param template 模版信息
     * @return 结果
     */
    @Override
    public int updateTemplate(GenTemplate template) {
        return baseMapper.updateById(template);
    }

    /**
     * 校验模版类型与名称是否唯一
     *
     * @param template 模板
     * @return String
     */
    @Override
    public String checkTemplateUnique(GenTemplate template) {
        long templateId = StringUtils.isNull(template.getTemplateId()) ? -1L : template.getTemplateId();
        // 模板类型相同，模板名称相等
        GenTemplate genTemplate = this.getOne(new LambdaQueryWrapper<GenTemplate>()
                .eq(GenTemplate::getTemplateType, template.getTemplateType())
                .eq(GenTemplate::getTemplateName, template.getTemplateName()));
        if (StringUtils.isNotNull(genTemplate) && genTemplate.getTemplateId() != templateId) {
            return Constants.CONFIG_KEY_NOT_UNIQUE;
        } else {
            return Constants.CONFIG_KEY_UNIQUE;
        }
    }

    /**
     * 批量删除代码生成模版
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteTemplateByIds(String ids) {
        Long[] templateIds = Convert.toLongArray(ids);
        for (Long templateId : templateIds) {
            GenTemplate template = this.getById(templateId);
            if (template.isBuiltIn()) {
                throw new BusinessException(String.format("内置模版【%1$s】不能删除 ", template.getTemplateName()));
            }
        }
        return this.baseMapper.deleteBatchIds(Arrays.asList(Convert.toStrArray(ids)));
    }

    @Override
    public void resetCache() {
        TemplateCacheUtils.removeAll();
    }

}
